package com.CST.config;

import com.CST.util.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;

import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:Swagger2API文档的配置
 * @Author: wzw
 * @Time: 2020/11/20 10:35
 */
@Configuration
@EnableSwagger2
@ConditionalOnProperty(prefix = "swagger", name = "button-open", havingValue = "true")
public class Swagger2Config {

	@Autowired
	private JwtConfig jwtConfig;

    @Bean
    public Docket createRestApi() {
		Map<String, Object> map = new HashMap<>();
		map.put("userName", "admin");
		map.put("userPassword","123456");
		//map.put("userId", "1");
		List<Parameter> parameters = new ArrayList<>();
		ParameterBuilder userName = new ParameterBuilder();
		ParameterBuilder userId = new ParameterBuilder();
		ParameterBuilder token = new ParameterBuilder();
		userName.name("userName").description("用户登录名").modelRef(new ModelRef("string")).parameterType("header");
		userId.name("userId").description("用户主键").modelRef(new ModelRef("string")).parameterType("header");
		//token.name("token").description("token令牌").modelRef(new ModelRef("string")).parameterType("header").defaultValue(jwtConfig.getToken(map));

		String tokenValue=JwtTokenUtil.generateToken(map);

		token.name("token").description("token令牌").modelRef(new ModelRef("string")).parameterType("header").defaultValue(tokenValue);


		parameters.add(userName.build());
		parameters.add(userId.build());
		parameters.add(token.build());

		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
				//为有@Api注解的Controller生成API文档
				.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
				//为有@ApiOperation注解的方法生成API文档
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any()).build().globalOperationParameters(parameters);
    }

    private ApiInfo apiInfo() {
	  return new ApiInfoBuilder().title("CST").description("CST").version("1.0").build();
    }
}
